package org.example.service.Impl;

import cn.hutool.jwt.JWTUtil;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.example.config.R;
import org.example.domain.Notifis;
import org.example.mapper.NotifisMapper;
import org.example.service.NotifisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class NotifisServiceImpl implements NotifisService {
    @Autowired
    NotifisMapper notifisMapper;
    @Override
    public List<Notifis> notifisList(Notifis notifis) {
        return notifisMapper.notifisList(notifis);
    }
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RocketMQTemplate rocketMQTemplate;
    @Autowired
    HttpServletRequest request;
    @Override
    public R notifisAdd(Notifis notifis,String username) {
        if(redisTemplate.hasKey("notifis:"+username)){
            return R.failed("禁止重复提交");
        }
        notifis.setCreateTime(new Date());
        notifis.setFlag(0);
        notifis.setUsername(username);

        notifisMapper.notifisAdd(notifis);

        redisTemplate.opsForValue().setIfAbsent("notifis:"+username,notifis,5, TimeUnit.MINUTES);

        GenericMessage<String> message = new GenericMessage<>("添加成功");
        rocketMQTemplate.asyncSend("tpc-zpy", message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                String success = "发送成功";
                System.out.println(success);
            }

            @Override
            public void onException(Throwable throwable) {
                String error = "发送失败";
                System.out.println(error);
            }
        });
        return R.successed(null);
    }

    @Override
    public R delById(Integer id) {
        notifisMapper.delById(id);
        return R.successed(null);
    }

    @Override
    public R delAll(Integer[] ids) {
        notifisMapper.delAll(ids);
        return R.successed(null);
    }

    @Override
    public R updateById(Notifis notifis) {
        notifisMapper.updateById(notifis);
        return R.successed(null);
    }
}
